/**   
 * Filename:    crawler.java   
 * Create at:   2016年3月28日 上午9:52:04   
 * Description:  
 * Modification History:   
 * Author      Version     Description   
 * ----------------------------------------------------------------- 
 * Garfield      1.0       1.0 Version   
 */
package pga2;

import java.io.IOException;

import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import pga2.tools.SYSINFO;
import pga2.tools.StringUtils;
import pga2.tools.TimeSec;
import pga2.tools.UrlFormat;

public class Crawler {

	public static void main(String[] args) {
		System.out.println(RunCrawler(args));
	}

	public static String RunCrawler(String[] args) {
		String INFO = "Please enter the correct operation order!";
		if (args[0].trim().indexOf("-") == -1 || args.length == 0) {
			return INFO;
		}
		if (args[0].trim().equals("-v")) {
			return SYSINFO.VERSIONINFO;
		}
		if (args[0].trim().equals("-h")) {
			return SYSINFO.HELPINFO;
		}
		if(args[0].trim().equals("-cw")){
			INFO = Fetcher.RunCralerCw(args);
			return INFO;
		}
		if(args[0].trim().equals("-ci")){
			INFO = Fetcher.CrawlerCI(args);
			return INFO;
		}
		
		if(args[0].trim().equals("-u")){
			INFO = RunCrawlerMethod(args);
			return INFO;
		}
		return INFO;
	}

	public static String RunCrawlerMethod(String[] args) {
		Document doc = RunCralerConn(args);
		String resul = doc.html();
		return resul;
	}

	public static Document RunCralerConn(String[] args) {
		Connection conn = null;
		Document doc = null;
		
		if (args[0].trim().equals("-u")) {
			String parm2 = args[1];
			parm2 = UrlFormat.URLINPUTFORMAT(parm2);
			if (StringUtils.IsUrl(parm2)) {
				parm2 = UrlFormat.URLINPUTFORMAT(parm2);
				conn = Jsoup.connect(parm2);
			}
		}
		
		for (int i = 2; i < args.length;) {
			String parm1 = args[i];
			String parm2 = args[i+1];

				if (StringUtils.IsEqual(parm1, "-header")) {
					String[] header = parm2.split("@");
					conn.header(header[0], header[1]);
				}

				if (StringUtils.IsEqual(parm1, "-cookie")) {
					conn.cookie("Cookie", parm2);
				}

				if (StringUtils.IsEqual(parm1, "-data")) {
					conn.method(Method.POST);
					conn.data(parm2);
				}

				if (StringUtils.IsEqual(parm1, "-proxy")) {
					String[] data = parm2.split(":");
					String ip = data[0];
					int port = Integer.valueOf(data[1]);
					conn.proxy(ip, port);
				}
				if (StringUtils.IsEqual(parm1, "-timesec")) {
					TimeSec.Timesec(Integer.valueOf(parm2));
				}
				i = i + 2;
			}
			
		conn.timeout(50000);
		conn.ignoreContentType(true);
		if (StringUtils.IsEqual(args[args.length-1], "-post")) {
			try {
				doc = conn.post();
				return doc;
			} catch (IOException e) {
				System.out.println("[ERROR]" + e.getMessage());
			}
		} else {
			try {
				doc = conn.get();
				return doc;
			} catch (IOException e) {
				System.out.println("[ERROR]" + e.getMessage());
			}
		}
		return doc;
	}
	
}
